package current;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock比Synchronized更加灵活
 */
public class ProducerCustomerModel2 {
    final static int MAX = 10;

    LinkedList<Integer> queue = new LinkedList<>();

    ReentrantLock lock = new ReentrantLock();
    Condition full = lock.newCondition();
    Condition empty = lock.newCondition();


    int readData() throws InterruptedException {
        // 模拟运算成本，需要消耗一定时间
        TimeUnit.MICROSECONDS.sleep((long) (Math.random() * 1000));
        return (int) Math.floor(Math.random());
    }

    // 生产者
    public void readDb() throws InterruptedException {
        lock.lock();
        if (queue.size() == MAX) {
            full.await();
            return;
        }
        int data = readData();
        if (queue.size() == 1) {
            empty.signalAll();
        }
        queue.add(data);
        lock.unlock();
    }

    // 消费者
    public void calculate() throws InterruptedException {
        lock.lock();
        if (queue.size() == 0) {
            empty.await();
            return;
        }
        Integer data = queue.remove();
        if (queue.size() == MAX - 1) {
            full.signalAll();
        }
        System.out.println("queue-size: " + queue.size());
        data *= 100;
        lock.unlock();
    }

    public static void main(String[] args) {
        ProducerCustomerModel2 model = new ProducerCustomerModel2();
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                while (true) {
                    try {
                        model.readDb();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        new Thread(() -> {
            while (true) {
                try {
                    model.calculate();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}
